package net.tensor.skynet.actity

import android.annotation.SuppressLint
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import com.google.android.material.floatingactionbutton.FloatingActionButton
import com.google.android.material.snackbar.Snackbar
import com.google.gson.Gson
import kotlinx.android.synthetic.main.activity_item_list.*
import kotlinx.android.synthetic.main.item_list.*
import kotlinx.coroutines.*
import net.tensor.skynet.R
import net.tensor.skynet.adapter.SkynetAdapter
import net.tensor.skynet.common.user.entity.User
import net.tensor.skynet.entity.DataContainer
import net.tensor.skynet.service.UserService
import net.tensor.skynet.utils.BaseUtils
import okhttp3.OkHttpClient
import java.io.InputStream
import java.util.*
import javax.net.ssl.SSLContext
import javax.net.ssl.X509TrustManager
import kotlin.coroutines.CoroutineContext

class ItemListActivity : AppCompatActivity(), CoroutineScope {

    //job用于控制协程,后面launch{}启动的协程,返回的job就是这个job对象
    private lateinit var job: Job
    private var baseUtils: BaseUtils? = null
    private var adapter: SkynetAdapter? = null

    //=======================
    private var stream: InputStream? = null
    private var trustManager: X509TrustManager? = null
    private var sslContext: SSLContext? = null
    private var okHttpClient: OkHttpClient? = null
    private var gson: Gson? = null
    private var retrofit: UserService? = null
    //=======================

    override fun onDestroy() {
        super.onDestroy()
        //当acitivity结束之后,我们不需要再请求网络了,结束当前协程
        job.cancel()
    }

    //继承CoroutineScope必须初始化coroutineContext变量
    // 这个是标准写法,+其实是plus方法前面表示job,用于控制协程,后面是Dispatchers,指定启动的线程
    override val coroutineContext: CoroutineContext
        get() = job + Dispatchers.Main

    //======================================================================
    private fun initNetwork() {
        job = Job()
        baseUtils = BaseUtils()
        stream = baseUtils!!.getInputStream(
            this,
            R.raw.server200
        )
        trustManager = baseUtils!!.getTrustManager(stream!!)
        sslContext = trustManager?.let { baseUtils!!.getSSLContext(it) }
        okHttpClient =
            sslContext?.let { trustManager?.let { it1 -> baseUtils!!.getOkHttpClient(it1, it) } }
        gson = baseUtils!!.getGson()
        retrofit = okHttpClient?.let {
            baseUtils!!.getRetrofit(
                it,
                "https://192.168.1.200:8080",
                gson ?: Gson()
            )
        }
    }
    //======================================================================

    @SuppressLint("Range")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        //=============================================================
        setContentView(R.layout.activity_item_list)
        val toolbar = findViewById<Toolbar>(R.id.toolbar)
        setSupportActionBar(toolbar)
        findViewById<FloatingActionButton>(R.id.fab).setOnClickListener { view ->
            Snackbar.make(view, "动作内容", Snackbar.LENGTH_LONG)
                .setAction("设置", null).show()
        }
        //=============================================================
        adapter = SkynetAdapter()
        setupRecyclerView()
        initNetwork()
        getData(0, 10)
        //===============================================================
        //设置下拉刷新和上拉加载监听
        refreshLayout.setDragRate(0.5f);//显示下拉高度/手指真实下拉高度=阻尼效果
        refreshLayout.setReboundDuration(300);//回弹动画时长（毫秒）
        refreshLayout.setEnableLoadMore(false);//是否启用上拉加载功能
        refreshLayout.setHeaderMaxDragRate(2F);//最大显示下拉高度/Header标准高度
        refreshLayout.setFooterMaxDragRate(2F);//最大显示下拉高度/Footer标准高度
        refreshLayout.setHeaderTriggerRate(1F)
        refreshLayout.setFooterTriggerRate(1F)
        refreshLayout.setEnableOverScrollBounce(true);//是否启用越界回弹

        //设置下拉刷新和上拉加载监听
        refreshLayout.setOnRefreshListener {
            //...替换数据
            getData(DataContainer.pageNum + 1, DataContainer.pageSize)
//            Snackbar.make(refreshLayout, "下拉加载更多内容", Snackbar.LENGTH_LONG)
//                .setAction("提示", null).show()
            it.finishRefresh()
        }
        refreshLayout.setOnLoadMoreListener {
            //...替换数据
//            getData(DataContainer.pageNum + 1, DataContainer.pageSize)
            it.finishLoadMore()
        }
    }

    private fun getData(page: Int, pageSize: Int) {
        launch {
            try {
                val map = mutableMapOf<String, Int>()
                map["page"] = page
                map["pageSize"] = pageSize
                val result = withContext(Dispatchers.IO) {
                    retrofit?.queryPage(
                        map
                    )?.execute()
                }
                if (result != null) {
                    if (result.isSuccessful) {
                        DataContainer.pageNum = result.body()?.pageNum ?: 0
                        DataContainer.pageSize = result.body()?.pageSize ?: 0
                        DataContainer.pages = result.body()?.pages ?: 0
                        DataContainer.total = result.body()?.total ?: 0
                        adapter?.replaceAll((result.body()?.list as ArrayList<User>))
                    } else {
                        adapter?.replaceAll(arrayListOf())
                    }
                }
            } catch (e: Exception) {
                adapter?.replaceAll(arrayListOf())
            }
        }
    }

    private fun setupRecyclerView() {
        item_list.adapter = adapter
    }
}